package com.wolfking.datasource;

import java.sql.Connection;
import java.util.Objects;

public class ThreadReuseContextUtils {


    private static final ThreadLocal<Boolean> reuseFlag = new InheritableThreadLocal<>();

    private static final ThreadLocal<ThreadReuseContext> contextThreadLocal = new InheritableThreadLocal<>();


    public static void setReuseTrue() {
        reuseFlag.set(true);
    }

    public static void setReuseFalse() {
        reuseFlag.set(false);
    }

    public static boolean isReuse() {
        Boolean aBoolean = reuseFlag.get();
        return Objects.nonNull(aBoolean) && aBoolean;
    }

    public static void setThreadReuseContext(Connection connection) {
        contextThreadLocal.set(new ThreadReuseContext(connection));
    }

    public static Connection reuseConnection() {
        ThreadReuseContext reuseContext = contextThreadLocal.get();
        if (Objects.nonNull(reuseContext) && reuseContext.canGet()) {
            return reuseContext.getConnection();
        }
        return null;
    }

    public static void useIncrease() {
        contextThreadLocal.get().increase();
    }

    public static void useDecrease() {
        contextThreadLocal.get().decrease();
    }

    public static boolean hasConnection() {
        ThreadReuseContext reuseContext = contextThreadLocal.get();
        return Objects.nonNull(reuseContext) && Objects.nonNull(reuseContext.getConnection());
    }

    public static void clearReuseContext() {
        reuseFlag.remove();
        ThreadReuseContext reuseContext = contextThreadLocal.get();
        contextThreadLocal.remove();
        if(Objects.nonNull(reuseContext)){
            try{
                reuseContext.getConnection().close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
